"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 一主两备在减容备1过程中停止备2
Create At   : 2022/03/03
Owner       : opentestcase023
Description :
    1.一主两备在减容备1过程中停止备2
    2.恢复环境，启动被关闭数据库
Expect      :
    1.备机减容失败
    2.环境恢复成功
History     :
    2022-5-17 opentestcase023 优化用例，根据自动化连跑要求，修改用例为在源库上减容
"""
import os
import time
import unittest
from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
primary_sh = CommonSH('PrimaryDbUser')
Constant = Constant()


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.standby1_root_node = Node('Standby1Root')
        self.standby1_node = Node('Standby1DbUser')
        self.standby2_root_node = Node('Standby2Root')
        self.standby2_node = Node('Standby2DbUser')
        self.u_name = self.primary_node.ssh_user
        self.ssh_file = os.path.join('/home', self.u_name, 'hostfile')
        num = primary_sh.get_node_num()
        self.assertGreaterEqual(num, 3, "执行失败:节点数量异常，减容不执行")

    def test_gs_dropnode(self):
        text = '----step1:在对备1减容时停止备2 expect:失败----'
        self.log.info(text)
        self.log.info('构建减容命令shell脚本前置条件')
        drop_cmd = f'gs_dropnode -U {self.u_name} -G {self.u_name} ' \
                   f'-h {self.standby1_node.ssh_host}'
        self.log.info(drop_cmd)
        global shell_path
        shell_path = os.path.join('/', 'home', f'{self.u_name}', 'dropnode.sh')
        shell_cmd = f'touch {shell_path};echo -e {drop_cmd} > {shell_path};' \
                    f'chmod 755 {shell_path};cat {shell_path}'
        self.log.info(shell_cmd)
        pri_shell_res = self.primary_root_node.sh(shell_cmd).result()
        sta1_shell_res = self.standby1_root_node.sh(shell_cmd).result()
        self.log.info(pri_shell_res)
        self.log.info(sta1_shell_res)
        self.log.info('对备1执行减容操作')
        drop_cmd = f'source {macro.DB_ENV_PATH};' \
                   f'{shell_path};'
        session_1 = ComThread(self.common.get_sh_result, args=(
            self.standby1_node, drop_cmd,))
        session_1.setDaemon(True)
        self.log.info('在备1减容同时停止备2')
        stop_cmd = f'source {macro.DB_ENV_PATH};' \
                   f'gs_om -t stop -h {self.standby2_node.ssh_host};'
        session_2 = ComThread(self.common.get_sh_result, args=(
            self.standby1_node, stop_cmd,))
        session_2.setDaemon(True)
        session_1.start()
        time.sleep(0.5)
        session_2.start()
        self.log.info('备1减容结果')
        session_1.join(120)
        session_1_result = session_1.get_result()
        self.log.info(session_1_result)
        self.log.info('备2停止结果')
        session_2.join(120)
        session_2_result = session_2.get_result()
        self.log.info(session_2_result)
        self.log.info('备1减容及备2停止结果')
        check_msg = f'[GAUSS-35803] The IP of local host ' \
                    f'{self.standby1_node.ssh_host} is in the target node list'
        self.assertIn(check_msg, session_1_result, '备1减容同时停止备2，减容错误')
        self.assertIn(Constant.STOP_NODE_SUC_MSG, session_2_result, '备2停止失败')

        self.log.info('检查数据库是否减容')
        check_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_om -t status --detail;'
        self.log.info(check_cmd)
        check_res = self.primary_node.sh(check_cmd).result()
        self.log.info(check_res)
        check_lis = [self.primary_node.ssh_host, self.standby1_node.ssh_host,
                     self.standby2_node.ssh_host]
        for info in check_lis:
            self.assertIn(info, check_res, '数据库状态检查失败')

    def tearDown(self):
        text = "----step2：恢复环境 expect:成功----"
        self.log.info(text)
        del_cmd = f'rm -rf {shell_path}'
        self.log.info(del_cmd)
        del_res = self.primary_root_node.sh(del_cmd).result()
        self.log.info(del_res)
        start_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_ctl start -D {macro.DB_INSTANCE_PATH} -M standby;' \
                    f'gs_ctl build -D {macro.DB_INSTANCE_PATH}'
        self.log.info(start_cmd)
        start_res = self.standby2_node.sh(start_cmd).result()
        self.log.info(start_res)
        self.assertIn('server started', start_res, '备2启动失败')
        self.assertEqual('', del_res, '文件删除失败')
        self.log.info(f'----{os.path.basename(__file__)} finish----')
